package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

/**
 * @program: itcast_health
 * @create: 2019-10-27 15:20
 * @author: li he
 * @description:
 */
@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private LoginService loginService;

    @RequestMapping("check")
    public Result check(@RequestBody Map<String, String> map){
        /*
        * 1.验证码验证用户
        * 2.查询会员是是否存在,如果不存在快速注册
        * 3.返回结果
        * */
        String validateCodeInParam = map.get("validateCode");
        String telephone = map.get("telephone");
        //1.验证码验证用户
        String validateCodeInRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_LOGIN+telephone);

        if (!(validateCodeInRedis != null && validateCodeInRedis.equals(validateCodeInParam))){
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
        try {
            //2.查询会员是是否存在,如果不存在快速注册
            Member member = loginService.findByTelephone(telephone);

            if (member == null) {
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                loginService.add(member);
            }
            //3.返回结果
            return new Result(true,MessageConst.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }
}